<template>
  <a-layout style="min-height: 100vh">
    <a-layout-sider collapsible v-model:collapsed="collapsed">
      <div class="logo">
        <span class="logo-title">健康管理助手</span>
      </div>
      <a-menu theme="dark" mode="inline" :openKeys="openKeys" :selectedKeys="selectedKeys" @openChange="onOpenChange" @click="onMenuClick">
        <a-sub-menu key="assistant" title="健康管理">
          <a-menu-item key="userProfile">个人主页</a-menu-item>
          <a-menu-item key="healthRecord">健康记录</a-menu-item>
        </a-sub-menu>
      </a-menu>
    </a-layout-sider>

    <a-layout>
      <a-layout-header class="header">
        <div class="user-info">
          <a-avatar style="background-color: #87d068; margin-right: 8px;">
            {{ userInitial }}
          </a-avatar>
          <span>{{ user.username }}</span>
          <span class="user-email">{{ user.email }}</span>
          <a-button type="link" @click="logout">退出登录</a-button>
        </div>
      </a-layout-header>

      <a-layout-content class="content-layout">
        <div class="content-box">
          <HealthRecord 
            v-if="activeTab === 'healthRecord'"
            :user="user"
          />
          <UserProfile 
            v-else-if="activeTab === 'userProfile'"
          />
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import HealthRecord from './HealthRecord.vue'
import UserProfile from '../../components/common/UserProfile.vue'



const collapsed = ref(false)
const openKeys = ref(['assistant'])
const selectedKeys = ref(['healthRecord'])
const activeTab = ref('healthRecord')
const router = useRouter()

// 计算属性
const user = computed(() => {
  return JSON.parse(localStorage.getItem('user') || '{}')
})

const userInitial = computed(() => {
  return user.value.username?.charAt(0).toUpperCase() || 'U'
})

function onMenuClick({ key }) {
  activeTab.value = key
  selectedKeys.value = [key]
}

function logout() {
  localStorage.removeItem('accessToken')
  localStorage.removeItem('refreshToken')
  localStorage.removeItem('user')
  router.replace('/')
}

function onOpenChange(keys) {
  openKeys.value = keys
}
</script>

<style scoped>
.logo {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #fff;
  font-weight: bold;
  margin: 16px 0;
}
.logo-title {
  letter-spacing: 2px;
}
.header {
  background: #fff;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 64px;
  box-shadow: 0 2px 8px #f0f1f2;
}
.user-info {
  display: flex;
  align-items: center;
  font-size: 16px;
}
.user-email {
  margin-left: 16px; 
  color: #888;
}
.content-layout {
  margin: 24px 16px 0;
}
.content-box {
  background: #fff;
  min-height: 360px;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
}
</style>